package com.cuanbobox.utils;

/**
 * 定时器
 */
public class TimerThread extends Thread {
    private long time;
    private boolean loop;
    private OnDoWorkListener onDoWorkListener;

    /**
     * 初始化定时器
     *
     * @param onDoWorkListener 每隔time毫秒执行一次该回调
     * @param time             回调执行的时间间隔，单位：毫秒
     */
    public TimerThread(OnDoWorkListener onDoWorkListener, long time) {
        loop = true;
        this.onDoWorkListener = onDoWorkListener;
        this.time = time;
        start();
    }

    @Override
    public void run() {
        super.run();
        while (loop) {
            if (onDoWorkListener != null) {
                onDoWorkListener.doWork();
            }
            try {
                Thread.sleep(time);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 停止计时器
     */
    public void stopTimer() {
        loop = false;
    }

    public interface OnDoWorkListener {
        void doWork();
    }
}
